<template>
  <div>
    <el-card>
      <div class="top-search">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="任务类名">
            <el-input v-model="formInline.user" placeholder="请输入任务类名" />
          </el-form-item>
          <el-form-item label="cron表达式">
            <el-input
              v-model="formInline.user"
              placeholder="请输入cron表达式"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card>
      <div class="btnList">
        <el-button type="primary" @click="addBtn(formAddAndEdit)"
          >增加</el-button
        >
      </div>
      <el-table
        :data="tableConfig.list"
        style="width: 100%"
        height="380"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column fixed type="selection" width="55" align="center" />
        <el-table-column
          fixed
          label="序号"
          type="index"
          width="70"
          align="center"
        />
        <el-table-column
          prop="className"
          label="任务类名"
          width="250"
          align="center"
        >
          <template #default="scope">
            <div class="modality" @click="hitDetail(scope.row.id)">
              {{ scope.row.className }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="scheduleConf"
          label="cron表达式"
          width="180"
          align="center"
        />
        <el-table-column prop="status" label="状态" align="center" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.status" type="success">启用</el-tag>
            <el-tag v-else>未启用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="executorParam"
          label="参数"
          align="center"
          width="300"
        />
        <el-table-column
          prop="jobDesc"
          label="描述"
          align="center"
          width="180"
        />

        <el-table-column
          prop="author"
          label="负责人"
          align="center"
          width="120"
        />
        <el-table-column
          prop="scheduleType"
          label="调度类型"
          align="center"
          width="150"
        />
        <el-table-column
          prop="address"
          label="创建人"
          align="center"
          width="120"
        />
        <el-table-column
          prop="createTime"
          label="创建时间"
          align="center"
          width="150"
        />
        <el-table-column
          prop="address"
          label="更新人"
          align="center"
          width="120"
        />
        <el-table-column
          prop="modifyTime"
          label="更新时间"
          align="center"
          width="150"
        />
        <el-table-column
          label="操作"
          align="center"
          fixed="right"
          :width="sizeWatchWidth"
        >
          <template #default="scope">
            <el-button type="success" @click="startBtn(scope.row.id)"
              >启动</el-button
            >
            <el-button @click="stopBtn(scope.row.id)">停止</el-button>
            <!-- <el-button @click="editBtn(scope.row)">编辑</el-button> -->
            <el-button type="danger" @click="delBtn(scope.row.id)"
              >删除</el-button
            >
            <el-dropdown style="margin-left: 12px">
              <el-button type="primary">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="execute(scope.row)"
                    >手动执行</el-dropdown-item
                  >
                  <el-dropdown-item @click="editBtn(scope.row)"
                    >编辑</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <Paging
        :total="total"
        :currentPage.sync="currentPage"
        :pageSize.sync="pageSize"
        @pagination="handlePageChange"
      ></Paging>
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      :title="flagEditOrAdd ? '修改定时任务' : '新增定时任务'"
      width="50%"
      :before-close="handleClose"
    >
      <div>
        <el-form :model="form" ref="formAddAndEdit" label-width="120px">
          <el-form-item label="任务编码">
            <!-- <el-input v-model="form.jobGroup"></el-input> -->
            <el-select
              v-model="form.jobGroup"
              clearable
              placeholder="请选择任务编码"
              style="width: 100%"
            >
              <el-option
                v-for="item in optionsList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="任务类名">
            <el-input v-model="form.className"></el-input>
          </el-form-item>
          <el-form-item label="cron表达式">
            <el-input v-model="form.scheduleConf"></el-input>
          </el-form-item>
          <el-form-item label="负责人">
            <el-input v-model="form.author"></el-input>
          </el-form-item>
          <el-form-item label="调度类型">
            <el-input v-model="form.scheduleType"></el-input>
          </el-form-item>
          <el-form-item label="参数">
            <el-input
              v-model="form.executorParam"
              :rows="3"
              type="textarea"
              placeholder="请输入参数"
            />
          </el-form-item>
          <el-form-item label="描述">
            <el-input
              v-model="form.jobDesc"
              :rows="3"
              type="textarea"
              placeholder="请输入描述"
            ></el-input>
          </el-form-item>

          <el-form-item label="状态">
            <el-switch
              v-model="form.status"
              size="large"
              active-text="启用"
              inactive-text="未启用"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="addTimedTask"> 保 存 </el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情弹框 -->
    <el-dialog
      v-model="dialogDetailVisible"
      title="运行状态"
      width="85%"
      draggable
      fullscreen
    >
      <el-card style="text-align: center; margin: 8px">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="任务名称">
            <el-input v-model="formInline.user" placeholder="请输入任务名称" />
          </el-form-item>
          <el-form-item label="任务组名">
            <el-select v-model="formInline.region" placeholder="请选择任务组名">
              <el-option label="Zone one" value="shanghai" />
              <el-option label="Zone two" value="beijing" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card style="margin: 8px">
        <el-table
          :data="tableConfig.detialList"
          style="width: 100%"
          height="450"
          border
        >
          <el-table-column
            type="index"
            label="序号"
            width="75"
            align="center"
          />
          <el-table-column prop="id" label="编号" width="180" align="center" />
          <el-table-column
            prop="jobName"
            label="任务名称"
            width="250"
            align="center"
          />
          <el-table-column
            prop="jobGroupName"
            label="任务组名"
            width="250"
            align="center"
          />
          <el-table-column
            prop="jobGroupName"
            label="任务运行参数"
            width="250"
            align="center"
          />
          <el-table-column
            prop="executorParam"
            label="目标参数"
            width="180"
            align="center"
          />
          <el-table-column
            prop="logInfo"
            label="日志信息"
            width="180"
            align="center"
          />
          <el-table-column
            prop="status"
            label="执行状态"
            width="180"
            align="center"
          >
            <template #default="scope">
              <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
              <el-tag v-else type="danger">失败</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="startTime"
            label="开始时间"
            width="220"
            align="center"
          />
          <el-table-column
            prop="executeTime"
            label="执行时间"
            width="120"
            align="center"
          />
        </el-table>

        <!-- 分页 -->
        <Paging
          :total="totalDetail"
          :currentPage.sync="page.mount"
          :pageSize.sync="page.size"
          @pagination="handlePageDetailChange"
        ></Paging>
      </el-card>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch, nextTick } from "vue";
import { ArrowDown } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
// 引入自定义请求库
import { postAction } from "@/utils/system/commonUse";
import { ElNotification, ElMessage } from "element-plus";
// Paging 组件
import Paging from "@/components/basePage/packagePaging/index.vue";
import { useStore } from "vuex";
import type { FormInstance } from "element-plus";
const store = useStore();
// 查看详情弹框
const dialogDetailVisible = ref(false);

const size = computed(() => store.state.app.elementSize);
const sizeWatchWidth = ref(300);
watch(
  () => store.state.app.elementSize,
  (newV, oldV) => {
    switch (newV) {
      case "default":
        sizeWatchWidth.value = 320;
        break;
      case "small":
        sizeWatchWidth.value = 300;
        break;
      case "large":
        console.log(1);

        sizeWatchWidth.value = 400;
        break;
    }
  }
);

console.log("size", size);

const form = reactive({
  id: "",
  jobGroup: "", //编码
  className: "",
  jobDesc: "", //任务描述
  author: "", //负责人
  scheduleConf: "", //cron
  executorParam: "", //参数
  scheduleType: "CRON", //调度类型
  status: false,
});
watch(
  () => form.status,
  (newV, oldV) => {
    console.log("newV,oldV", newV, oldV);
  }
);

const optionsList = ref(Array());
// 默认false 代表添加
const flagEditOrAdd = ref(false);
// 获取表单实例
const formAddAndEdit = ref();
const addBtn = (formEl: FormInstance | undefined) => {
  // getjobGroupList();

  flagEditOrAdd.value = false;
  dialogVisible.value = true;
  form.id = "";
  formEl?.resetFields();
  // console.log("formEl?.resetFields", formEl?.resetFields);

  nextTick(() => {
    // console.log("formAddAndEdit", formAddAndEdit.value.resetFields);
    // formAddAndEdit.value.resetFields();
  });
};

const editBtn = (row: any) => {
  form.id = row.id;
  form.jobGroup = row.jobGroup;
  form.className = row.className;
  form.jobDesc = row.jobDesc;
  form.author = row.author;
  form.scheduleConf = row.scheduleConf;
  form.executorParam = row.executorParam;
  form.scheduleType = row.scheduleType;
  form.status = row.status;
  flagEditOrAdd.value = true;
  dialogVisible.value = true;
};

const url = reactive({
  addUrl: "http://192.168.5.88:8080/job/addJob",
  getListUrl: "http://192.168.5.88:8080/job/listJob",
  startJobUrl: "http://192.168.5.88:8080/job/startJob",
  stopJobUrl: "http://192.168.5.88:8080/job/stopJob",
  delJobUrl: "http://192.168.5.88:8080/job/deleteJob",
  uplJobUrl: "http://192.168.5.88:8080/job/reSchedulerJob",
  detailUrl: "http://192.168.5.88:8080/jobLog/listJobLog",
  manualOperationUrl: "http://192.168.5.88:8080/job/runJob",
});
onMounted(() => {
  getjobGroupList();
});

// 启动定时任务
const startBtn = (id: string) => {
  console.log(`${url.startJobUrl}/${id}}`);

  postAction(url.startJobUrl, { id })
    .then((data: any) => {
      console.log("启动定时任务===>", data);
      if (data.code != 1000) {
        return ElMessage.error(data.msg);
      }
      getjobGroupList();
      ElMessage({
        message: data.msg,
        type: "success",
      });
    })
    .catch((err) => {
      console.log(err);
      ElMessage.error("启动失败");
    });
};
// 暂停任务
const stopBtn = (id: string) => {
  postAction(url.stopJobUrl, { id })
    .then((data: any) => {
      console.log("暂停定时任务===>", data);
      if (data.code != 1000) {
        return ElMessage.error(data.msg);
      }
      getjobGroupList();
      ElMessage({
        message: data.msg,
        type: "success",
      });
    })
    .catch((err) => {
      console.log(err);
      ElMessage.error("暂停失败");
    });
};
// 手动执行
const execute = (row: any) => {
  ElMessageBox.confirm("是否启动?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "success",
  })
    .then(() => {
      postAction(url.manualOperationUrl, { id: row.id })
        .then((data: any) => {
          if (data.code != 1000) {
            return ElMessage.error(data.msg);
          }
          getjobGroupList();
          ElMessage({
            type: "success",
            message: data.msg,
          });
        })
        .catch((err) => {
          console.log(err);
          ElMessage.error("启动失败");
        });
    })
    .catch(() => {});
};
// 删除定时任务
const delBtn = (id: string) => {
  ElMessageBox.confirm("是否删除此定时任务?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      postAction(url.delJobUrl, { id })
        .then((data: any) => {
          if (data.code != 1000) {
            return ElMessage.error(data.msg);
          }
          getjobGroupList();
          ElMessage({
            message: data.msg,
            type: "success",
          });
        })
        .catch((err) => {
          console.log(err);
          ElMessage.error("删除失败");
        });
    })
    .catch(() => {});
};

const addTimedTask = () => {
  // 进入代表新增
  if (!flagEditOrAdd.value) {
    postAction(url.addUrl, form)
      .then((data: any) => {
        console.log("data", data);

        if (data.code != 1000) {
          return ElMessage.error(data.msg);
        }
        ElMessage.success(data.msg);
        getjobGroupList();
        dialogVisible.value = false;
      })
      .catch((err) => {
        console.log(err);
      });
  } else {
    // 修改
    postAction(url.uplJobUrl, form)
      .then((data: any) => {
        console.log("data", data);

        if (data.code != 1000) {
          return ElMessage.error(data.msg);
        }
        ElMessage.success(data.msg);
        getjobGroupList();
        dialogVisible.value = false;
      })
      .catch((err) => {
        console.log(err);
      });
  }
};
// 表格数据
const tableConfig = reactive({
  list: Array(), //外层列表数据
  detialList: Array(), // 详情弹框列表信息
});
const getjobGroupList = () => {
  postAction(url.getListUrl, {
    size: pageSize.value,
    mount: currentPage.value,
  })
    .then((data: any) => {
      // console.log("data===>", data);

      if (data.code != 1000) {
        return ElMessage.error(data.msg);
      }
      // 赋值
      tableConfig.list = data.data.data;

      // dialogVisible.value = false;
    })
    .catch((err) => {
      console.log(err);
    });
};
// 新增模态框
const dialogVisible = ref(false);

const handleClose = (done: () => void) => {
  done();
};

const multipleSelection = ref(Array());
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
};

// 条数
const total = ref(0);
// 长度
const pageSize = ref(10);
// 页码
const currentPage = ref(1);

// 分页器
const handlePageChange = (data: any) => {
  console.log("data", data);

  currentPage.value = data.currentPage;
  pageSize.value = data.pageSize;
  // getList();
};
// 点击详情后 存储id
const rowId = ref("");
// 查看详情
const hitDetail = (id: string) => {
  rowId.value = id;
  getjobDetailList(id);
  dialogDetailVisible.value = true;
};

const totalDetail = ref(0);
const page = reactive({
  size: 10,
  mount: 1,
});
const handlePageDetailChange = (data: any) => {
  page.mount = data.currentPage;
  page.size = data.pageSize;
  getjobDetailList(rowId.value);
};

const formInline = reactive({
  user: "",
  region: "",
});

const onSubmit = () => {
  console.log("submit!");
};

// 查看详情数据
const getjobDetailList = (id: string) => {
  postAction(url.detailUrl, Object.assign({ id }, page))
    .then((data: any) => {
      console.log("data===>", data);

      if (data.code != 1000) {
        return ElMessage.error(data.msg);
      }
      // // 赋值
      tableConfig.detialList = data.data.data;
      totalDetail.value = data.data.count;

      // dialogVisible.value = false;
    })
    .catch((err) => {
      console.log(err);
    });
};
</script>

<style lang="scss" scoped>
.el-card {
  margin: 15px;
}
.top-search {
  display: flex;
}

.btnList {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-start;
}

// 模拟样式
.modality {
  cursor: pointer;
  color: #1890ff;
}
</style>
